<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>权限管理</title>
    <script src="/vue/vue.js"></script>
    <script src="/axios/axios.min.js"></script>
    <script src="/qs/qs.min.js"></script>
    <script src="/elementui/index.js"></script>
    <link rel="stylesheet" href="/elementui/index.css">
</head>
<body>
    <div id="app">
        <el-row>
            <el-button type="primary" @click="showTreeDialog">角色授权</el-button>
            <el-button type="primary" @click="showAddDialog">角色添加</el-button>
        </el-row>
        <hr style="height: 0px;color: gainsboro">
        <template>
            <el-table
                    ref="roleTable"
                    :data="tableData"
                    height="449"
                    border
                    stripe
                    tooltip-effect="dark"
                    style="width: 100%"
                    :header-cell-style="{background:'#B3C0D1',color:'#ffffff'}"
                    @selection-change="handleSelectionChange"
                    @select-all="selectAll"
                    @select="select"
                    @current-change="changeCurrentRole">
                <el-table-column
                        fixed
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="id"
                        label="编号"
                        width="150">
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        label="角色">
                </el-table-column>
                <el-table-column
                        prop="roleDescribe"
                        label="描述">
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="200">
                    <template slot-scope="scope">
                        <el-button
                                size="normal"
                                @click="editRole(scope.$index, scope.row)">编辑</el-button>
                        <el-button
                                size="normal"
                                type="danger"
                                @click="deleteRole(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @prev-click="prev"
                    @next-click="next"
                    @current-change="currentChange"
                    background
                    layout="prev, pager, next"
                    :total="total"
                    :current-page="current"
                    :page-size="pageSize">
            </el-pagination>
        </template>

<!--        树形对话框-->
        <el-dialog
                title="角色授权"
                :visible.sync="dialogTreeVisible"
                width="30%"
                :close-on-click-modal="false"
                @close="closeTreeDialog">
            <el-tree
                    :data="functions"
                    show-checkbox
                    node-key="id"
                    ref="tree"
                    @check="checkClick"
                    highlight-current
                    :default-checked-keys="idArr"
                    :default-expanded-keys="idArr"
                    :props="defaultProps">
            </el-tree>
        </el-dialog>

<!--        表单对话框-->
        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="closeRoleDialog">
            <el-form :model="role">
                <el-form-item label="角色" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入角色"
                            v-model="role.roleName"
                            autocomplete="off"
                            clearable
                            maxlength="10"
                            show-word-limit
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
                <el-form-item label="描述" :label-width="formLabelWidth">
                    <el-input
                            placeholder="请输入角色描述"
                            v-model="role.roleDescribe"
                            autocomplete="off"
                            clearable
                            maxlength="100"
                            show-word-limit
                            style="width: 50%;">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole" :style="{display: addBtnShow}">添加</el-button>
                <el-button type="primary" @click="modifyRole" :style="{display: modifyBtnShow}">修改</el-button>
            </div>
        </el-dialog>
    </div>
</body>
<script>
    var Main = {
        data() {
            return {
                tableData: [],  //表格数据
                current:1,  //当前行
                total:1,    //总行数
                pageSize:10,    //页码
                pages:1,    //总页数
                currentRole:null,   //当前选中角色
                multipleSelection: [],
                dialogTreeVisible:false, //显示权限树对话框
                functions:null, //权限数据
                idArr: [],    //默认当前选中的角色所有的权限
                defaultProps: { //修改树属性的名称
                    children: 'menusSon',
                    label: 'menuName'
                },
                dialogFormVisible: false,
                role: {
                    roleName: '',
                    roleDescribe: ''
                },
                formLabelWidth: '120px',
                dialogTitle: '添加角色',
                addBtnShow:'',
                modifyBtnShow:'none',
            }
        },
        methods: {
            //分页上一页
            prev(current){
                this.getPage(current);
            },
            //分页下一页
            next(current){
                this.getPage(current);
            },
            //分页当前页点击
            currentChange(current){
                this.getPage(current);
            },
            //点击选择用户
            //加载数据
            getPage(current){
                axios.get("/roles?current="+current).then(value => {
                    if (value.data.state==1){
                        this.tableData = value.data.data.records;
                        this.current = value.data.data.current;
                        this.total = value.data.data.total;
                        this.pageSize = value.data.data.size;
                        this.pages = value.data.data.pages;
                    }else {
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //加载权限
            getFunctions(){
                axios.get("/functions").then(value => {
                    if (value.data.state==1){
                        console.log(value);
                        this.functions = value.data.data;
                    }
                });
            },
            //当前列改变时
            changeCurrentRole(row){
                this.currentRole = row;
                //取消所有的选择效果
                this.$refs.roleTable.clearSelection();
                //选中当前的行
                this.$refs.roleTable.toggleRowSelection(row);
            },
            //全选按钮
            selectAll(){
                this.$refs.roleTable.clearSelection();
            },
            //选择当前checkbox时
            select(selection,row){
                this.changeCurrentRole(row);
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            getIdArr(id){
                //id数组
                let idArr = [];
                //通过角色id获得权限
                axios.get("/function",{params:{roleId:id}}).then(value => {
                    console.log(value);
                    //返回的权限
                    let functions = value.data.data;
                    for (let fun of functions) {
                        idArr.push(fun.id);
                    }
                    //赋给默认选中
                    this.idArr = idArr;
                })
            },
            //显示授权对话框
            showTreeDialog(){
                if (this.currentRole){
                    //获取当前选中用户的id
                    let id = this.currentRole.id;
                    this.getIdArr(id);
                    this.dialogTreeVisible = true;
                }else {
                    this.sendMessage("请选择用户！","warning");
                }
            },
            //添加权限
            addFun(funIdArr){
                let param = new URLSearchParams();
                param.append('roleId',this.currentRole.id);
                param.append('funIdArr',funIdArr);
                axios.post(
                    "/roleFun",param).then(value => {
                    if (value.data.state==1){
                        this.sendMessage("修改权限成功","success");
                    }else{
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //删除权限
            deleteFun(funIdArr){
                let param = new URLSearchParams();
                param.append('roleId',this.currentRole.id);
                param.append('funIdArr',funIdArr);
                axios.delete("/roleFun",{params:param}).then(value => {
                    if (value.data.state==1){
                        this.sendMessage("修改权限成功","success");
                    }else{
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //复选框选中
            checkClick(data,objArr){
                let funIdArr = [];

                //1、判断是选中还是取消选中
                let flat = false;   //true为选中（添加），false为取消（删除）
                //遍历已选中的数组，判断当前选择节点是否存在
                for (let obj of objArr.checkedNodes) {
                    if (obj == data){
                        flat = true;
                        break;
                    }
                }

                //添加当前节点
                funIdArr.push(data.id);

                //2、判断是否为半选中
                if (objArr.halfCheckedKeys.length!=0){

                    //是半选中：即不是全选

                    if (flat){
                        // 添加：添加当前选中节点
                        this.addFun(funIdArr);
                    }else {
                        // 删除：删除当前取消的节点和父节点
                        funIdArr.push(objArr.halfCheckedKeys[0]);
                        this.deleteFun(funIdArr);
                    }

                }else {

                    //不是半选中：即全选
                    // 第一种：是父节点且之前是全未选中状态，添加父节点和父节点的所有子节点
                    // 第二种：是父节点且之前是半选中状态，
                    // 第三种：不是父节点，添加当前选中节点以及当前选中节点的父节点（当前节点的pid值）

                    //判断是否有子节点
                    if (data.menusSon != null){
                        for (let sonFunction of data.menusSon) {
                            funIdArr.push(sonFunction.id);
                        }
                    }else {
                        funIdArr.push(data.pid);
                    }

                    if (flat){

                        // 添加：把父节点和父节点的所有子节点都传过去，后端去判断
                        this.addFun(funIdArr);
                    }else {

                        // 删除：删除父节点和父节点的所有子节点
                        this.deleteFun(funIdArr);
                    }
                }

            },
            //关闭对话框
            closeTreeDialog(){
                //清除所有选中节点
                this.$refs.tree.setCheckedKeys([]);
                //清除所有展开的节点
                this.$refs.tree.store._getAllNodes().forEach(node => {
                    node.expanded = false;
                })
            },
            //打开角色的对话框
            showAddDialog(){
                this.dialogFormVisible = true;
                this.dialogTitle = '添加角色';
                this.addBtnShow = '';
                this.modifyBtnShow = 'none';
            },
            //关闭角色对话框
            closeRoleDialog(){
                this.role.id = '';
                this.role.name = '';
                this.role.description = '';
                this.getPage(this.current);
            },
            //修改角色
            editRole(index,row){
                //显示对话框
                this.dialogFormVisible = true;
                //修改对话框标题
                this.dialogTitle = '修改角色'
                //显示修改按钮，隐藏添加按钮
                this.addBtnShow = 'none';
                this.modifyBtnShow = '';
                //回显选中的角色信息
                this.role.id = row.id;
                this.role.roleName = row.roleName;
                this.role.roleDescribe = row.roleDescribe;
            },
            //删除角色
            deleteRole(index,row){
                if (confirm("确定删除吗?")){
                    axios.delete("/role/"+row.id).then(value => {
                        if (value.data.state==1){
                            //弹出框提示添加成功
                            this.sendMessage("删除成功","success");
                            //刷新页面
                            //判断是否为最后一页
                            if (this.current == this.pages && this.current > 1){
                                //判断是否为最后一条数据
                                if (this.total%this.pageSize==1){
                                    this.current -= 1;
                                }
                            }
                            this.getPage(this.current);
                        }
                    });
                }else {
                    this.sendMessage("出错啦","error");
                }
            },
            //添加角色
            addRole(){
                axios.post("/role",this.role).then(value => {
                    if (value.data.state==1){
                        //弹出框提示添加成功
                        this.sendMessage("添加成功","success");
                        //关闭弹出框
                        this.dialogFormVisible = false;
                    }else {
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //修改用户
            modifyRole(){
                axios.put("/role",this.role).then(value => {
                    if (value.data.state==1){
                        //弹出框提示
                        this.sendMessage("修改成功","success");
                        //关闭弹出框
                        this.dialogFormVisible = false;
                    }else {
                        this.sendMessage("出错啦","error");
                    }
                });
            },
            //提示信息
            sendMessage(msg,type){
                this.$message({
                    showClose: true,
                    message: msg,
                    type: type
                });
            }
        },
        mounted(){
            //加载数据
            this.getPage(1);
            this.getFunctions();
        }
    }
    var Ctor = Vue.extend(Main)
    new Ctor().$mount('#app')
</script>
</html>